package com.jessechanrui.template.projectcase.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * @author chenrui
 * @date 2024/1/30
 */

@Configuration(value = "okhttp")
public class OkHttpConfig {
    @Value("${okhttp.proxy.enable}")
    private boolean enable;

    @Value("${okhttp.proxy.host}")
    private String proxyHost;

    @Value("${okhttp.proxy.port}")
    private int proxyPort;

    @Value("${okhttp.connectTimeout}")
    private int connectTimeout;

    @Value("${okhttp.readTimeout}")
    private int readTimeout;

    @Value("${okhttp.writeTimeout}")
    private int writeTimeout;

    /**
     * 连接池的最大空闲连接数
     */
    @Value("${okhttp.connectionPool.maxConnect}")
    private int maxConnect;

    /**
     * 每个连接的最大请求数
     */
    @Value("${okhttp.connectionPool.keepAlive}")
    private int keepAlive;

    @Bean
    public OkHttpClient okHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .callTimeout(connectTimeout, TimeUnit.SECONDS)
                //设置连接超时时间
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                // 设置读取超时时间
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                // 设置写入超时时间
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                // 是否自动重试连接失败的请求
                .retryOnConnectionFailure(false)
                // 设置连接池;
                .connectionPool(new ConnectionPool(maxConnect, keepAlive, TimeUnit.MINUTES));
        if (enable) {
            builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        }
        return builder.build();
    }
}
